<!--
* description: 展车订单(新增，编辑)
* author: wangjuan
* createdDate:2020-11-12
-->
<template>
  <section class="editSetBelowAdd">
    <el-dialog
      v-dialogDrag
      v-loading="editloading"
      :visible.sync="curPopupsVisible"
      :title="textMap[popupsState]"
      :append-to-body="true"
      width="70%"
      :close-on-click-modal="false"
      @close="closeEdit"
    >
      <dialogHeader
        slot="title"
        :title="textMap[popupsState]"
        :style-type="$store.state.app.dialogType"
      />

      <div class="filter-container filter-title">展车单信息</div>
      <div class="filter-container filter-params">
        <el-row ref="vailComponentList1" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents1.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :custom-obj="comp.customObj"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :data-to-object="comp.dataToObj"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div class="filter-container filter-title">订单明细添加</div>
      <div class="filter-container filter-params">
        <el-row ref="vailComponentList2" :gutter="26">
          <component
            :is="comp.component"
            v-for="comp in tableComponents2.filter(o => o.isMust === true)"
            :ref="comp.isRequire ? comp.isRequire + comp.compKey : comp.compKey"
            :key="comp.compKey"
            :validrule="comp.validrule"
            :code-field="comp.codeField"
            :text-field="comp.textField"
            :popups-key="comp.compKey"
            :parent-fileds="comp.parentFileds"
            :code="formField[comp.codeField]"
            :disabled="comp.disabled"
            :o-fields="comp.oFields"
            :options="comp.options"
            :custom-obj="comp.customObj"
            :is-require="comp.isRequire"
            :is-mul="comp.isMul"
            :span="comp.span || 8"
            :label-name="comp.labelName"
            :lookuptype="comp.lookuptype"
            :date-options-type="comp.dateOptionsType"
            @changeCode="getComponentCode"
            @focusCode="getFocusCode"
          />
        </el-row>
      </div>

      <div class="app-container app-container-table">
        <one-table-template
          ref="multipleTable"
          :dynamic-buttons="dynamicTableButtons"
          :dynamic-table-cols="tableCols"
          :dynamic-api-config="apiConfig"
          :dynamic-form-fields="formField"
          :dynamic-is-init-table="true"
          :dynamic-is-show-select="false"
          :dynamic-is-show-more-btn="true"
          :dynamic-table-defult-height="300"
        />
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button
          v-for="comp in tableButtons"
          :key="comp.compKey"
          :type="comp.type"
          :icon="comp.icon"
          :fixed="true"
          @click="comp.clickEvent"
        >{{ comp.text }}</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import { formMixins } from '@/components/mixins/formMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import api from '@/api/belowInfo'
// import apis from '@/api/subsidyManage'
import { setDynamicFieldsData } from '@/utils/dataOperation'

export default {
  components: {
    dialogHeader: () => import('@/components/dialogHeader'),
    OneTableTemplate
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins, formMixins],

  props: {
    dynamicEditRowData: { type: Object, default: () => { return {} } },
    // 弹出是否显示
    popupsVisible: { type: Boolean, default: false },
    customObj: { type: Object, default: () => { return {} } }
  },

  data() {
    const viewPageCode = 'belowOrd-Edit'
    return {
      editloading: false,
      multable: 'multipleTable1',
      showBtn: '1', // 开关
      transferOrderDId: [],
      updateControlIdD: [],

      dataRefs: ['truecompKey2', 'truecompKey3'],
      apiConfig: api.queryExhibitionCarProductionByDetail,
      // 动态组件-按钮
      dynamicTableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.addRow(),
          text: '添加',
          isShow: true
        },
        {
          compKey: 'btnKey2',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: (index) => this.saveEdit(index),
          text: '保存编辑',
          isShow: false
        },
        {
          compKey: 'btnKey3',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.cancelEdit(),
          text: '取消编辑',
          isShow: false
        }
      ],
      tableButtons: [
        {
          compKey: 'btnKey1',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.save(),
          text: this.$t('sys.button.save')
        },
        {
          compKey: 'btnKey2',
          size: 'small',
          naem: 'cancel',
          icon: 'iconfont icon-cancel',
          clickEvent: () => this.closeEdit(1),
          text: this.$t('sys.button.cancel')
        }
      ],
      tableComponents: this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents.length > 0
        ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
        : [],
      // 动态组件-查询条件
      tableComponents1:
        this.$ConfigCache.CacheConfig.cacheData[viewPageCode] &&
          this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[viewPageCode].formComponents
          : [
            {
              compKey: 'compKey1',
              labelName: '批次编号：',
              codeField: 'transferOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey2',
              labelName: '负责人姓名：',
              codeField: 'chargeMen',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey3',
              labelName: '负责人电话：',
              codeField: 'chargePhone',
              validrule: { isPhone: true, maxlength: 11 },
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              isMul: false,
              isMust: true,
              span: 8
            },
            {
              compKey: 'compKey4',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true,
              span: 24
            }
          ],

      tableComponents2: [
        {
          compKey: 'compKey5',
          labelName: '车系：',
          codeField: 'carSeriesId',
          textField: 'carSeriesCn',
          oFields: 'carSeriesId,carSeriesCn',
          component: () => import('@/components/org/commonSelect'),
          customObj: {
            api: api.listOfCarSeries,
            selectType: '1'
          },
          type: 'dropdownList',
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey6',
          labelName: '基础车型：',
          codeField: 'carConfigId',
          textField: 'carConfigCn',
          oFields: 'carConfigId,carConfigCn',
          component: () => import('@/components/org/commonSelect'),
          customObj: {
            api: api.queryCarType,
            listQuery: {
              carSeriesId: ''
            },
            selectType: '1'
          },
          parentFileds: 'disabled:carSeriesId-carConfigId--false,value:carSeriesId',
          type: 'dropdownList',
          disabled: true,
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey7',
          labelName: '选装包：',
          codeField: 'optionalPagId',
          textField: 'optionalPagName',
          component: () => import('@/components/org/commonSelect'),
          oFields: 'optionalPagId,optionalPagName',
          customObj: {
            api: api.queryCarOptionalPagLinkMessage,
            listQuery: {
              carConfigId: ''
            },
            selectType: '1'
          },
          parentFileds: 'disabled:carConfigId-optionalPagId--false,value:carConfigId-carConfigId',
          type: 'dropdownList',
          disabled: true,
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey8',
          labelName: '车身颜色：',
          codeField: 'carColorId',
          textField: 'carColorName',
          component: () => import('@/components/org/commonSelect'),
          oFields: 'carColorId,carColorName',
          customObj: {
            api: api.queryCarColorLinkMessage,
            listQuery: {
              carConfigId: '',
              optionalPagId: ''
            },
            selectType: '1'
          },
          parentFileds: 'disabled:optionalPagId-carColorId--false,value:carConfigId|optionalPagId',
          type: 'dropdownList',
          disabled: true,
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey9',
          labelName: '内饰颜色：',
          codeField: 'carIncolorId',
          textField: 'carIncolorName',
          component: () => import('@/components/org/commonSelect'),
          oFields: 'carIncolorId,carIncolorName',
          customObj: {
            api: api.queryCarInColorLinkMessage,
            listQuery: {
              carConfigId: '',
              optionalPagId: ''
            },
            selectType: '1'
          },
          parentFileds: 'disabled:optionalPagId-carIncolorId--false,value:carConfigId|optionalPagId',
          type: 'dropdownList',
          disabled: true,
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey10',
          labelName: '交付门店：',
          codeField: 'deliveryDlrShortName',
          textField: 'deliveryDlrId',
          component: () => import('./deliveryCity'),
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey11',
          labelName: '展车门店：',
          codeField: 'dlrShortName',
          textField: 'dlrId',
          component: () => import('@/views/ve/salesStore/below.vue'),
          type: 'inputText',
          isMust: true,
          isRequire: true,
          span: 8
        },
        {
          compKey: 'compKey12',
          labelName: '数量：',
          codeField: 'orderNum',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isRequire: true,
          isMust: true,
          span: 8
        },
        {
          compKey: 'compKey13',
          labelName: '交付城市：',
          codeField: 'cityName',
          textField: 'cityId',
          component: () => import('@/components/org/commonInput'),
          isMust: true,
          disabled: true,
          isRequire: true,
          span: 8
        },
        {
          compKey: 'compKey14',
          labelName: '备注：',
          codeField: 'remark02',
          component: () => import('@/components/org/commonInput'),
          type: 'inputText',
          isMust: true,
          span: 24
        }
      ],

      tableCols: [
        {
          prop: 'releaseId',
          label: '主键ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlIdO',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'updateControlIdOd',
          label: '并发控制ID',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'transferOrderId',
          label: '展车主单id',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'transferOrderDId',
          hidden: true,
          alwaysHidden: true
        },
        {
          prop: 'controlBtn',
          label: '操作',
          codeField: 'controlBtn',
          width: 100,
          align: 'center',
          fixed: true,
          isComponent: true,
          comps: [
            {
              compKey: 'propKey0',
              align: 'center',
              labelName: '编辑',
              clickEvent: (index) => this.handleEdit(index),
              component: () => import('@/components/org/linkButton')
            },
            {
              compKey: 'propKey1',
              align: 'center',
              labelName: '删除',
              clickEvent: (index) => this.handleDelete(index),
              component: () => import('@/components/org/linkButton')
            }
          ]
        },
        {
          prop: 'carSeriesCn',
          label: '车系',
          align: 'center'
        },
        {
          prop: 'carConfigCn',
          label: '基础车型',
          align: 'center'
        },
        {
          prop: 'optionalPagName',
          label: '选装包',
          align: 'center'
        },
        {
          prop: 'carColorName',
          label: '车身颜色',
          align: 'center'
        },
        {
          prop: 'carIncolorName',
          label: '内饰颜色',
          align: 'center'
        },
        {
          prop: 'cityName',
          label: '交付城市',
          align: 'center'
        },
        {
          prop: 'deliveryDlrShortName',
          label: '交付门店',
          align: 'center'
        },
        {
          prop: 'dlrShortName',
          label: '展车门店',
          align: 'center'
        },
        {
          prop: 'orderNum',
          label: '数量',
          align: 'center'
        },
        {
          prop: 'remark02',
          label: '备注',
          align: 'center'
        }
      ],
      formField: {
        carSeriesId: '',
        carConfigId: '',
        optionalPagId: '',
        carColorId: '',
        carIncolorId: '',
        cityId: '',
        deliveryDlrId: '',
        dlrId: '',
        orderNum: '',
        carSeriesCn: '',
        carConfigCn: '',
        optionalPagName: '',
        carColorName: '',
        carIncolorName: '',
        cityName: '',
        deliveryDlrShortName: '',
        dlrShortName: '',
        remark02: '',
        updateControlIdO: '',
        updateControlIdOd: '',
        transferOrderDId: '',
        chargeMen: '',
        chargePhone: '',
        remark: '',
        transferOrderCode: '',
        transferOrderId: ''
      },
      // 标题
      textMap: {
        edit: '修改订单',
        add: '新增订单',
        view: '查看订单'
      },
      dataList: [],
      cIndex: 0
    }
  },
  watch: {
    'formField.cityId': {
      handler: function(val) {
        if (val) {
          console.log(this.tableComponents2[8])
        }
      }
    },
    curPopupsVisible(val) {
      // debugger
      if (val) {
        if (this.popupsState === 'edit') {
          const queryObj = {
            type: 'mutation',
            apiConfig: api.queryExhibitionCarProductionByDetail,
            variables: { transferOrderId: this.formField.transferOrderId }
          }
          var paramD = this.$getParams(queryObj)
          this.$requestAPI(paramD).then(response => {
            if (response.result === '1') {
              const list = response.rows
              this.$refs.multipleTable.list = list
              this.$refs.multipleTable.pageTotal = this.$refs.multipleTable.list.length
              this.dataList = list
            }
          })
        }
      }
    }
  },

  created() {
    this.tableComponents = [...this.tableComponents1, ...this.tableComponents2]
  },

  mounted() {
    this.$nextTick(() => {
      this.formField = Object.assign(this.formField, this.dynamicEditRowData)
    })
  },

  methods: {
    // 清除验证
    resetOrderIcon() {
      this.$nextTick(() => {
        for (const comp in this.$refs) {
          if (comp.includes('true')) {
            this.$refs[comp][0].$children[0].$children[2].iconV = '3'
          }
        }
      })
    },

    // 添加
    addRow() {
      // debugger
      this.$utils.validataMoth(this, 'validpopup', undefined, 'multipleTable')
      if (this.valid) {
        this.$refs.multipleTable.list.push(this.$utils.deepCopy(this.formField))
        this.$refs.multipleTable.pageTotal = this.$refs.multipleTable.list.length
        this.$message({
          message: '添加成功',
          duration: 1000
        })
      }
    },

    // 保存编辑
    saveEdit() {
      this.$utils.validataMoth(this, 'validpopup', undefined, 'multipleTable')
      if (this.valid) {
      // debugger
        var dataList = this.$utils.deepCopy(this.$refs.multipleTable.list)
        for (let i = 0; i < dataList.length; i++) {
        // if (this.cIndex === dataList[i].transferOrderDId) {
        //   var datas = this.$utils.deepCopy(this.formField)
        //   dataList[i] = datas
        // }
          if (this.cIndex === i.toString()) {
            dataList[i] = this.$utils.deepCopy(this.formField)
          }
        }
        this.$refs.multipleTable.list = this.$utils.deepCopy(dataList)
        this.$message({
          message: '编辑成功',
          duration: 1000
        })
        // 显示隐藏按钮
        this.showBtn = '1'
        this.dynamicTableButtons.forEach((v, i) => {
          if (v.isShow) {
            v.isShow = false
          } else {
            v.isShow = true
          }
        })
        this.resetOrderIcon()
        this.resetData()
      }
    },

    // 取消编辑
    cancelEdit() {
      // debugger
      this.showBtn = '1'
      this.dynamicTableButtons.forEach((v, i) => {
        if (v.isShow) {
          v.isShow = false
        } else {
          v.isShow = true
        }
      })
      this.resetOrderIcon()
      this.resetData()
    },
    // 清空
    resetData() {
      this.$utils.deepClone(this.formField)
      this.formField.carSeriesId = ''
      // this.formField.chargeMen = ''
      // this.formField.chargePhone = ''
      this.formField.carSeriesCn = ''
      this.formField.carConfigId = ''
      this.formField.carConfigCn = ''
      this.formField.optionalPagId = ''
      this.formField.optionalPagName = ''
      this.formField.carColorId = ''
      this.formField.carColorName = ''
      this.formField.carIncolorId = ''
      this.formField.carIncolorName = ''
      this.formField.cityId = ''
      this.formField.cityName = ''
      this.formField.deliveryDlrId = ''
      this.formField.deliveryDlrShortName = ''
      this.formField.dlrShortName = ''
      this.formField.dlrId = ''
      this.formField.orderNum = ''
      this.formField.remark02 = ''
    },

    // 子单-编辑
    handleEdit(index) {
      this.cIndex = index
      // debugger
      if (this.showBtn === '1') {
        this.dynamicTableButtons.forEach((v, i) => {
          if (v.isShow) {
            v.isShow = false
          } else {
            v.isShow = true
          }
        })
      }
      this.showBtn = 0
      // 回填数据-onetable
      setDynamicFieldsData(this.formField, this.$refs.multipleTable.list[index])
    },

    // 子单-删除
    handleDelete(index) {
      this.transferOrderDId.push(this.$refs.multipleTable.list[index].transferOrderDId)
      this.updateControlIdD.push(this.$refs.multipleTable.list[index].updateControlIdOd)
      this.$confirm('确认删除该数据？', '提示', {
        type: 'warning'
      }).then(() => {
        const delDatas = this.$refs.multipleTable.list
        delDatas.splice(index, 1)
        this.$refs.multipleTable.pageTotal = this.$refs.multipleTable.list.length
        this.$message({
          message: '删除成功',
          duration: 1000
        })
      })
    },

    // 新增/编辑保存按钮
    save() {
      const that = this
      this.$utils.validataMoth(this, 'validpopup', undefined, 'multipleTable', undefined, function(refs) {
        const vpage = {}
        for (const ref in refs) {
          this.dataRefs.includes(ref) ? vpage[ref] = refs[ref] : ''
        }
        return vpage
      })
      if (that.valid) {
        that.editloading = true
        if (that.popupsState === 'edit') {
          that.editSave()
        } else {
          that.addSave()
        }
      }
    },

    // 编辑保存
    editSave() {
      const that = this
      const queryObj = {
        type: 'mutation',
        apiConfig: api.updateExhibitionCarProduction,
        variables: {
          data: that.$refs.multipleTable.list,
          chargeMen: that.formField.chargeMen,
          chargePhone: that.formField.chargePhone,
          remark: that.formField.remark,
          transferOrderId: that.dynamicEditRowData.transferOrderId,
          updateControlIdO: that.dynamicEditRowData.updateControlIdO
          // updateControlIdOd: that.formField.updateControlIdOd,
          // transferOrderDId: this.transferOrderDId,
          // updateControlIdD: this.updateControlIdD
        }
      }
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then(response => {
        that.editloading = false
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            duration: 1000
          })
          this.$emit('update:popupsVisible', false)
          this.$parent.$refs.multipleTable.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            duration: 1000
          })
        }
        this.$emit('update:popupsVisible', false)
      })
    },

    // 新增保存
    addSave() {
      const that = this
      const queryObj = {
        type: 'mutation',
        apiConfig: api.insertExhibitionCarProduction,
        variables: {
          data: that.$refs.multipleTable.list,
          chargeMen: that.formField.chargeMen,
          chargePhone: that.formField.chargePhone,
          remark: that.formField.remark
        }
      }
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then(response => {
        that.editloading = false
        if (response.result === '1') {
          this.$message({
            message: response.msg,
            duration: 1000
          })
          this.$emit('update:popupsVisible', false)
          this.$parent.$refs.multipleTable.queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            duration: 1000
          })
        }
        this.$emit('update:popupsVisible', false)
      })
    },
    // 关闭弹窗
    // handleClose(done) {
    //   this.$confirm('还未保存，是否确认关闭窗口？', '提示', {
    //     type: 'warning'
    //   })
    //     .then(_ => {
    //       this.$emit('update:popupsVisible', false)
    //       done()
    //     })
    //     .catch(_ => {})
    // },

    closeEdit() {
      this.clearData()
      this.resetOrderIcon()
      this.$emit('update:popupsVisible', false)
    }
  }
}
</script>

<style lang="scss" scoped>
  .filter-title{
    font-size: 18px;
    font-weight: bolder;
  }
  .filter-container.filter-title::before{
    border-left: 4px solid #0075FF;
    padding-right: 10px;
    height: 20px;
    left: 0px;
    top: 4px;
  }
  /deep/.el-dialog{
    height: 720px;
  }
</style>
